//
//  UPPersonalViewController.m
//  Uang Pasti
//
//  Created by 李永彬 on 2025/8/25.
//

#import "UPPersonalViewController.h"
#import "UPPersonalAddressCustomView.h"
#import "UPPersonalListView.h"
#import "UPEnumCustomView.h"

@interface UPPersonalViewController ()<UPPersonalAddressCustomViewDelegate, UPEnumCustomViewDelegate>

@property (nonatomic, strong) UPCustomAlertView *customAlertView;
@property (nonatomic, strong) UPPersonalListView *personalListView;
@property (nonatomic, strong) PersonalLapidantModel *personalLapidantModel;
@property (nonatomic, strong) PersonalBlackModel *currentPersonalBlackModel;
@property (nonatomic, strong) UIButton *continueButton;
@property (nonatomic, assign) double startTime;

@end

@implementation UPPersonalViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    [self commonInitSubviews];
    [self fetchPersonalData];
    self.startTime = [[NSDate date] timeIntervalSince1970];
}

- (void)fetchPersonalData {
    [SVProgressHUD show];
    [UPStocksAPIManager fetchPersonalInfoWithProductId:self.currentOmniosity.degreeaneous completion:^(PersonalLapidantModel * _Nonnull lapidantModel, NSString * _Nonnull msg) {
        if (lapidantModel) {
            self.personalLapidantModel = lapidantModel;
            self.personalListView.dataSources = lapidantModel.black;
            [SVProgressHUD dismiss];
        } else {
            [SVProgressHUD showInfoWithStatus:msg];
        }
    }];
}

- (void)fetchSavePersonalData {
    [SVProgressHUD show];
    [UPStocksAPIManager fetchSavePersonalInfoWithProductId:self.currentOmniosity.degreeaneous lapidantModel:self.personalLapidantModel completion:^(BOOL successs, NSString * _Nonnull msg) {
        if (successs) {
            [SVProgressHUD dismiss];
            NSDictionary *dic = @{
                @"followUpData": self.currentOmniosity
            };
            [[NSNotificationCenter defaultCenter] postNotificationName:kFollowUpMyOrderKey
                                                                object:nil
                                                              userInfo:dic];
            [UPReportDataManager reportToMaiDian:UPSceneTypePersonalCredential
                                       productId:self.currentOmniosity.degreeaneous
                                      productNum:self.currentOmniosity.viciacity
                                  startTimeStamp:self.startTime
                                    endTimeStamp:[[NSDate date] timeIntervalSince1970]];
        } else {
            [SVProgressHUD showInfoWithStatus:msg];
        }
        
    }];
}

- (void)commonInitSubviews {
    self.personalListView = [[UPPersonalListView alloc] init];
    __block typeof(self) weakSelf = self;
    self.personalListView.cellArrowButtonBlock = ^(PersonalBlackModel * _Nullable model, BOOL isAddress) {
        [weakSelf.view endEditing:YES];
        weakSelf.currentPersonalBlackModel = model;
        if (isAddress) {
            [weakSelf showAddressAlert];
        } else {
            [weakSelf showEnumAlert];
        }
    };
    
    self.personalListView.cellTextFieldChangedBlock = ^(PersonalBlackModel * _Nullable model, NSString * _Nullable text) {
        model.propriics = text;
        weakSelf.currentPersonalBlackModel = model;
    };

    [self.view addSubview:self.personalListView];
    UIImage *bgImage = [UIImage imageNamed:@"presonal_list_bg"];
    CGFloat bgAspectRatio = bgImage.size.width / bgImage.size.height;
    CGFloat bgWidth = kScreenWidth - 2 * 16;
    CGFloat bgHeight = bgWidth / bgAspectRatio;
    [self.personalListView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.collectionView.mas_bottom).offset(30);
        make.centerX.equalTo(self.view);
        make.width.mas_equalTo(bgWidth);
        make.height.mas_equalTo(bgHeight);
    }];
    
    UIImage *buttonImage = [UIImage imageNamed:@"button_bg_style5"];
    CGFloat buttonHeight = 50.0;
    CGFloat buttonAspectRatio = buttonImage.size.width / buttonImage.size.height;
    CGFloat buttonWidth = buttonHeight * buttonAspectRatio;
    [self.continueButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(self.view).offset(- bottomsafeArea());
        make.centerX.equalTo(self.view);
        make.height.mas_equalTo(buttonHeight);
        make.width.mas_equalTo(buttonWidth);
    }];
}

- (void)showAddressAlert {
    UPPersonalAddressCustomView *customView = [[UPPersonalAddressCustomView alloc] init];
    UIImage *bgImage = [UIImage imageNamed:@"address_bg"];
    CGFloat bgAspectRatio = bgImage.size.width / bgImage.size.height;
    CGFloat bgWidth = kScreenWidth - 2 * 16;
    CGFloat bgHeight = bgWidth / bgAspectRatio;
    customView.frame = CGRectMake(0, 0, bgWidth, bgHeight);
    customView.delegate = self;
    if ([AppConfig sharedInstance].appCountryEnv == AppCountryEnvIndonesia ){
        customView.addressPicker.maxLevel = 3;
    } else {
        customView.addressPicker.maxLevel = 2;
    }
    NSData *modelData = [UPUserDefaults objectForKey:myAddressKey];
    if (modelData) {
        NSError *error = nil;
        ADRLapidantModel *model = [NSKeyedUnarchiver unarchivedObjectOfClass:[ADRLapidantModel class]
                                                                    fromData:modelData
                                                                       error:&error];
        if (error) {
            NSLog(@"解码失败: %@", error.localizedDescription);
        } else {
            NSLog(@"解码成功: %@", model);
        }
        
        [customView.addressPicker loadCountryAddress:model];
    }
    
    UPCustomAlertView *alert = [[UPCustomAlertView alloc] initWithCustomView:customView style:UPAlertViewStyleBottomSheet];
    [alert showInView:self.view];
    self.customAlertView = alert;
}

- (void)showEnumAlert {
    UPEnumCustomView *customView = [[UPEnumCustomView alloc] init];
    UIImage *bgImage = [UIImage imageNamed:@"address_bg"];
    CGFloat bgAspectRatio = bgImage.size.width / bgImage.size.height;
    CGFloat bgWidth = kScreenWidth - 2 * 16;
    CGFloat bgHeight = bgWidth / bgAspectRatio;
    customView.frame = CGRectMake(0, 0, bgWidth, bgHeight);

    customView.delegate = self;
    customView.personalBlackModel = self.currentPersonalBlackModel;
    UPCustomAlertView *alert = [[UPCustomAlertView alloc] initWithCustomView:customView style:UPAlertViewStyleBottomSheet];
    [alert showInView:self.view];
    self.customAlertView = alert;
}

- (UIButton *)continueButton {
    if (!_continueButton) {
        _continueButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [_continueButton setBackgroundImage:[UIImage imageNamed:@"button_bg_style5"] forState: UIControlStateNormal];
        [_continueButton setTitle:LocalizableForKey(@"Continue certification") forState:UIControlStateNormal];
        [_continueButton setTitleColor:[UIColor colorWithHexString:@"#000000"] forState:UIControlStateNormal];
        _continueButton.titleLabel.font = [UIFont systemFontOfSize:14 weight:400];
        [_continueButton addTarget:self action:@selector(clickContinueButton) forControlEvents:UIControlEventTouchUpInside];
        [self.view addSubview:_continueButton];
    }
    return _continueButton;
}

#pragma mark - Method
- (void)clickContinueButton {
    [self fetchSavePersonalData];
}


#pragma mark -UPPersonalAddressCustomViewDelegate
- (void)addressCustomView:(UPAddressPickerView *)picker didClickConfirmButton:(NSArray<UPDataItem *> *)path {
    
    if (path.count != picker.maxLevel) {
        [SVProgressHUD showInfoWithStatus:LocalizableForKey(@"Please select the complete address")];
        return;
    }
    
    NSArray<NSString *> *nameArray = [path valueForKeyPath:@"name"];
    NSString *resultString = [nameArray componentsJoinedByString:@"-"];
    self.currentPersonalBlackModel.propriics = resultString;
    [self.personalListView reloadData];
    [self.customAlertView dismiss];
}

#pragma mark - UPEnumCustomViewDelegate
- (void)enumCustomView:(UPEnumCustomView *)enumView didSelectItemAtIndex:(NSInteger)index model:(PersonalEveryablyModel *)everyablyModel {
    self.currentPersonalBlackModel.propriics = everyablyModel.quindecimlocalety;
    self.currentPersonalBlackModel.tergmost = everyablyModel.tergmost;
    [self.personalListView reloadData];
    [self.customAlertView dismiss];
}

@end
